package com.chd.driversystem.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.anderson.dashboardview.view.DashboardView;
import com.chd.driversystem.R;
import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.domain.DrivingRecord;
import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.Oil;
import com.chd.driversystem.domain.Operation;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.Constants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class DriverActivity extends BaseActivity {
    public static final String TAG = "DriverActivity";

    private static DecimalFormat df = new DecimalFormat("0.0");

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;

    @BindView(R.id.btn_offline)
    Button btn_back;

    @BindView(R.id.iv_avator)
    CircleImageView civAvator;

    @BindView(R.id.tv_username)
    TextView tvUsername;

    @BindView(R.id.tv_userjob)
    TextView tvJob;

    @BindView(R.id.tv_usercode)
    TextView tvCode;

    @BindView(R.id.tv_userphone)
    TextView tvPhone;

    @BindView(R.id.tv_useremail)
    TextView tvEmail;

    @BindView(R.id.ibtn_location)
    ImageButton ibtnLocation;

    @BindView(R.id.ibtn_ranking)
    ImageButton ibtnRanking;

    @BindView(R.id.dv_tscore)
    DashboardView dvTscore;

    @BindView(R.id.tv_vehcode)
    TextView tvVehCode;

    //第一行
    @BindView(R.id.tv_distance)
    TextView tvDistance;

    @BindView(R.id.tv_drivingtime)
    TextView tvDrivingTime;

    @BindView(R.id.tv_maxspeed)
    TextView tvMaxSpeed;

    @BindView(R.id.tv_avespeed)
    TextView tvAveSpeed;
    //第二行

    @BindView(R.id.tv_rapidacc)
    TextView tvRapidAcc;

    @BindView(R.id.tv_rapiddec)
    TextView tvRapidDec;

    @BindView(R.id.tv_overspeedtime)
    TextView tvOverSpeedTime;

    @BindView(R.id.tv_shiftcount)
    TextView tvShiftCount;

    //第三行
    @BindView(R.id.tv_rpmcount)
    TextView tvRpmCount;

    @BindView(R.id.tv_sfdriving)
    TextView tvSfDriving;

    @BindView(R.id.tv_cfdriving)
    TextView tvCfDriving;

    @BindView(R.id.tv_tdistance)
    TextView tvTDistance;

    @BindView(R.id.tv_brakecount)
    TextView tvBrakeCount;

    @BindView(R.id.tv_fuel)
    TextView tvFuel;

    @BindView(R.id.tv_totalfuel)
    TextView tvTotalFuel;

    @BindView(R.id.tv_avefuel)
    TextView tvAveFuel;

    @BindView(R.id.tv_oillevel)
    TextView tvOilLevel;

    private void viewInit() {
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Constants.ACTION_LOGOUT);
                sendBroadcast(intent);
            }
        });
        User user = MyApplication.getUser();

        tvUsername.setText(user.getName());

        if (user.getIsManager()) {
            tvJob.setText("管理员");
        } else {
            tvJob.setText("司机");
        }

        tvCode.setText(user.getCode());

        if (!TextUtils.isEmpty(user.getPhoneNum())) {
            tvPhone.setText(user.getPhoneNum());
        } else {
            tvPhone.setText("未设置");
        }

        if (!TextUtils.isEmpty(user.getEmail())) {
            tvEmail.setText(user.getEmail());
        } else {
            tvEmail.setText("未设置");
        }

        initDashBoard();

        ibtnRanking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RankingActivity.actionStart(DriverActivity.this);
            }
        });

        dvTscore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EvaluationActivity.actionStart(DriverActivity.this, MyApplication.getUser().getId(),
                        Evaluation.WEEK_EVALUATION);
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> results = new HashMap<>();
                DrivingRecord drivingRecord = BeanServer.getInstance()
                        .getLastDrivingRecordByUserId(MyApplication.getUser().getId());
                results.put("drivingRecord", drivingRecord);

                Operation operation = BeanServer.getInstance()
                        .getLastOperationByUserId(MyApplication.getUser().getId());
                results.put("operation", operation);

                Oil oil = BeanServer.getInstance()
                        .getOilLastByUserId(MyApplication.getUser().getId());
                results.put("oil", oil);

                NetMsg netMsg = new NetMsg(NetMsg.MAIN, HttpConstants.ACTION_DRIVINGRECORD,
                        HttpConstants.RESULT_OK, null, 0, 0);
                netMsg.setObj(results);
                EventBus.getDefault().post(netMsg);

                EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_EVALUATION,
                        HttpConstants.RESULT_OK, null, 1, 1));
            }
        }).start();
    }

    private void initDashBoard() {
        /**************************仪表盘********************************/
        //dvTotalOil.setLayoutParams(new RelativeLayout.LayoutParams(100,100));
        dvTscore.setText("评测总分");
        dvTscore.setTextSize(25);
        dvTscore.setTextColor(Color.BLACK);
        dvTscore.setUnit("分");
//        TimeInterpolator interpolator = new TimeInterpolator() {
//            @Override
//            public float getInterpolation(float input) {
//                return 0;
//            }
//        };
//        dvTotalOil.setInterpolator(interpolator);//设置动画插值器，从而达到不同的动画效果
        dvTscore.setStartColor(Color.RED);
        dvTscore.setEndColor(Color.GREEN);//如果设置了起始颜色和结束颜色，进度条会变成渐变色
        dvTscore.setStartNum(0);
        dvTscore.setMaxNum(100);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_driver:

                break;
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        toolbar.setTitle("司机");
        toolbar.setContentInsetStartWithNavigation(450);
        setSupportActionBar(toolbar);

        //后台服务参数
        params = new HashMap<>();
        params.put(Constants.EXTRA_PARAM1, Evaluation.WEEK_EVALUATION);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.home);
        }

        viewInit();

    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, DriverActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshList(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.MAIN) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATION:
                    Integer tscore = (Integer) netMsg.getObj();
                    dvTscore.setPercent(tscore);
                    break;
                case HttpConstants.ACTION_DRIVINGRECORD:
                    Map<String, Object> results = (Map<String, Object>) netMsg.getObj();
                    DrivingRecord drivingRecord = (DrivingRecord) results.get("drivingRecord");
                    if (drivingRecord != null) {
                        tvAveSpeed.setText(drivingRecord.getAveSpeed() + "km/h");
                        tvCfDriving.setText(drivingRecord.getCfDriving().toString());
                        tvDistance.setText(drivingRecord.getDistance() + "km");
                        tvMaxSpeed.setText(drivingRecord.getMaxSpeed() + "km/h");
                        tvSfDriving.setText(drivingRecord.getSfDriving().toString());
                        tvTDistance.setText(drivingRecord.getTDistance() + "km");
                        tvDrivingTime.setText(drivingRecord.getTtDriving() + "h");
                        tvOverSpeedTime.setText(drivingRecord.getTtOverspeed() + "h");
                    }

                    Operation operation = (Operation) results.get("operation");
                    if (operation != null) {
                        tvBrakeCount.setText(operation.getBrake().toString());
                        tvRapidAcc.setText(operation.getRapidAcc().toString());
                        tvRapidDec.setText(operation.getRapidDec().toString());
                        tvRpmCount.setText(operation.getRpm().toString());
                        tvShiftCount.setText(operation.getShift().toString());
                    }

                    Oil oil = (Oil) results.get("oil");
                    if (oil != null) {
                        tvFuel.setText(df.format(oil.getFuel()) + "L");
                        tvTotalFuel.setText(df.format(oil.getTotalFuel()) + "L");
                        tvOilLevel.setText(df.format(oil.getOilLevel()) + "L");
                        tvAveFuel.setText(df.format(oil.getAveFuel()) + "L");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void receiverNetMsg(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.BACKGROUND) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATION:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            Evaluation evaluation = BeanServer.getInstance()
                                    .getLastEvaluationByType(MyApplication.getUser().getId()
                                            , Evaluation.WEEK_EVALUATION);
                            if (evaluation!=null) {
                                Integer tscore = evaluation.getTScore();
                                netMsg.setObj(tscore);
                                netMsg.setType(NetMsg.MAIN);
                            }
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                case HttpConstants.ACTION_DRIVINGRECORD:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            Map<String, Object> results = new HashMap<>();
                            DrivingRecord drivingRecord = BeanServer.getInstance()
                                    .getLastDrivingRecordByUserId(MyApplication.getUser().getId());
                            results.put("drivingRecord", drivingRecord);

                            Operation operation = BeanServer.getInstance()
                                    .getLastOperationByUserId(MyApplication.getUser().getId());
                            results.put("operation", operation);

                            Oil oil = BeanServer.getInstance()
                                    .getOilLastByUserId(MyApplication.getUser().getId());
                            results.put("oil", oil);

                            netMsg.setObj(results);
                            netMsg.setType(NetMsg.MAIN);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
